
package com.superhelper.printer.task;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.superhelper.common.domain.Task;
import com.superhelper.common.mapper.TaskMapper;

public class TaskListener {
    @Autowired
    private TaskDispatcher dispatcher;

    @Autowired
    private TaskMapper taskMapper;

    private static Logger log = LoggerFactory.getLogger(TaskListener.class);
    private static final int FIXED_THREAD_SIZE = 2;
    private TaskThreadPool pool = new TaskThreadPool(FIXED_THREAD_SIZE, "task.listener");

    public void init() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                for (int i = 0; i < FIXED_THREAD_SIZE; i++) {
                    log.debug("start threads for task dispatch, count: {}", i);
                    pool.execute(new Runnable() {
                        @Override
                        public void run() {
                            while (true) {
                                try {
                                    List<Task> tasks = taskMapper.getExcutableTask(10, 20);
                                    if (CollectionUtils.isEmpty(tasks)) {
                                        Thread.sleep(500);
                                    } else {
                                        for (Task task : tasks) {
                                            if (0 < taskMapper.occupyTask(task.getId(), task.getRetryTimes())) {
                                                dispatcher.doService(task);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    log.warn("exception in task dispatch thread!", e);
                                    try {
                                        Thread.sleep(100);
                                    } catch (InterruptedException ie) {
                                        log.warn("exception when making dispatch thread sleep!", ie);
                                    }
                                }
                            }
                        }
                    });
                }
            }
        }, 1000);

    }
}
